"""
@date: 2023/8/20
@author: North
@file: 装饰器
@desc: test

"""
import functools

# 判断用户是否登录
user = None


# 从文件中读取用户信息
def read_user_info(filename):
    user_info = {}
    try:
        with open(filename, 'r') as file:
            lines = file.readlines()
            for line in lines:
                username, password = line.strip().split(':')
                user_info[username] = password
    except FileNotFoundError:
        pass
    return user_info


# 注册用户
def regist_user(username, password):
    with open("./userinfo.txt", 'a') as file:
        file.write(f"{username}:{password}\n")


# 登录用户
def login(username, password):
    global user
    user_info = read_user_info("./userinfo.txt")

    if username in user_info and user_info[username] == password:
        user = username
        print("登录成功！")
    else:
        print("登录失败！")


# 登出用户
def logout():
    global user
    user = None
    print("已登出！")


# 装饰器判断是否登录
def login_required(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        if user is None:
            print("请先登录再访问")
        else:
            func(*args, **kwargs)

    return wrapper


@login_required
def index():
    print("欢迎访问首页")


while True:
    choice = input("1. 登录 2. 登出 3. 注册 4. 访问首页 5. 退出：")
    if choice == '1':
        username = input("请输入用户名：")
        password = input("请输入密码：")
        login(username, password)
    elif choice == '2':
        logout()
    elif choice == '3':
        username = input("请输入用户名：")
        password = input("请输入密码：")
        regist_user(username, password)
    elif choice == '4':
        index()
    elif choice == '5':
        break
    else:
        print("无效的选项")
